<?php

namespace Modules\DataCheck\Services;

use Illuminate\Support\Facades\Cache;

/**
 * 任务进度服务
 */
class TaskProcessService
{
    /**
     * 最大值
     * @var int
     */
    private int $maxProcess = 100;

    /**
     * 最小值
     * @var int
     */
    private int $minProcess = 0;

    /**
     * 缓存key
     * @var string
     */
    private string $key;

    public function __construct(string $key = '')
    {
        if (!empty($key)) {
            $this->init($key);
        }
    }

    /**
     * 初始化
     * @param string $key
     * @return TaskProcessService
     */
    public function init(string $key): static
    {
        $this->key = $key;
        $this->set(0);
        return $this;
    }

    /**
     * 增加
     * @param int $num
     * @return $this
     */
    public function incr(int $num = 1): static
    {
        if ($num == 0) {
            return $this;
        }

        $this->set($this->get() + $num);
        return $this;
    }

    /**
     * 减
     * @param int $num
     * @return $this
     */
    public function decr(int $num): static
    {
        if ($num == 0) {
            return $this;
        }

        $this->set($this->get() - $num);
        return $this;
    }

    /**
     * 获取缓存
     * @param string $key
     * @return int
     */
    public function get(string $key = ''): int
    {
        return (int)Cache::get($key ?: $this->key);
    }

    /**
     * 设置
     * @param int $num
     * @return $this
     */
    public function set(int $num): static
    {
        $num = min(max($this->minProcess, $num), $this->maxProcess);
        Cache::put($this->key, $num);
        return $this;
    }

    /**
     * 判断缓存是否存在
     * @param string $key
     * @return bool
     */
    public function has(string $key = ''): bool
    {
        return Cache::has($key ?: $this->key);
    }

    /**
     * 获取当前进度
     * @param string $key
     * @return $this
     */
    public function delete(string $key = ''): static
    {
        Cache::forget($key ?: $this->key);
        return $this;
    }
}